<template>
    <div>
        <el-text size="large">库存信息</el-text>
        <el-divider style="margin: 10px 0;"></el-divider>
        <el-form :model="queryForm" label-width="120px" style="max-width: 100%; margin: 0 auto;">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="商品ID">
                        <el-input-number v-model="queryForm.goods_id as number" :min="0" :step="1" step-strictly placeholder="请输入ID" style="width: 100%;"></el-input-number>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="名字">
                        <el-autocomplete v-model="queryForm.goods_name" :fetch-suggestions="fetchSuggestions('goods_name')" placeholder="请输入商品名字"></el-autocomplete>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="预警阈值">
                        <el-input-number v-model="queryForm.warning_threshold as number" :min="0" :step="1" step-strictly placeholder="预警阈值" style="width: 100%;"></el-input-number>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="库存状态">
                        <el-select v-model="queryForm.stock_status" placeholder="请选择库存状态" clearable>
                            <el-option label="充足" value="充足"></el-option>
                            <el-option label="紧张" value="紧张"></el-option>
                            <el-option label="缺货" value="缺货"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="备注">
                        <el-autocomplete v-model="queryForm.remarks" :fetch-suggestions="fetchSuggestions('remarks')" placeholder="请输入备注"></el-autocomplete>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item>
                        <el-button type="primary" @click="searchStock" :loading="loading" :icon="Search">查询</el-button>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item>
                        <el-button type="success" @click="openAddDialog" :icon="Plus">新增</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <el-divider style="margin: 0px 0;"></el-divider>
        <el-row :gutter="20" v-if="stockCountStore.outOfStockCount > 0 || stockCountStore.lowStockCount > 0">
            <el-col :span="12">
                <el-card>
                    <div slot="header">
                        <el-badge :value="stockCountStore.outOfStockCount" class="badge" type="danger" :offset="[10,5]">
                            <span>缺货商品种类数量</span>
                        </el-badge>
                    </div>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card>
                    <div slot="header">
                        <el-badge :value="stockCountStore.lowStockCount" class="badge" type="danger" :offset="[10,5]">
                            <span>紧张商品种类数量</span>
                        </el-badge>
                    </div>
                </el-card>
            </el-col>
        </el-row>
        <el-divider style="margin: 0px 0;"></el-divider>
        <el-table :data="paginatedStockList" v-if="paginatedStockList.length > 0" :row-class-name="tableRowClassName">
            <el-table-column prop="goods_id" label="商品ID" sortable></el-table-column>
            <el-table-column prop="goods_name" label="名字" sortable></el-table-column>
            <el-table-column prop="warning_threshold" label="预警阈值" sortable></el-table-column>
            <el-table-column prop="stock_quantity" label="库存数量" sortable></el-table-column>
            <el-table-column prop="stock_status" label="库存状态" sortable>
                <template #default="scope">
                    <el-icon :color="getStatus(scope.row.stock_status).color" size="large" style="vertical-align: -25%;">
                            <component :is="getStatus(scope.row.stock_status).icon"></component>
                        </el-icon>
                    <el-tag round effect="dark" :type="getStatus(scope.row.stock_status).type as any">
                        {{ scope.row.stock_status }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="remarks" label="备注" sortable></el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-container style="width: 4.5rem;">
                        <el-button type="primary" :icon="Edit" circle @click="openEditDialog(scope.row)"></el-button>
                        <el-button type="danger" :icon="Delete" circle @click="openDeleteDialog(scope.row)"></el-button>
                    </el-container>
                </template>
            </el-table-column>
        </el-table>
        <el-empty v-else description="没找到数据呢，亲~"></el-empty>
        <el-pagination
            v-if="total > 0"
            :current-page="currentPage"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            @current-change="handlePageChange"
            @size-change="handleSizeChange">
        </el-pagination>
        <AddDialog ref="addStockDialog" @refresh="searchStock" />
        <EditDialog ref="editStockDialog" @refresh="searchStock" />
        <DeleteDialog ref="deleteStockDialog" @refresh="searchStock" />
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import AddDialog from '@/components/AddDialog.vue';
import EditDialog from '@/components/EditDialog.vue';
import DeleteDialog from '@/components/DeleteDialog.vue';
import type { StockQueryForm, Stock, FormItem } from '@/types/interface';
import { CircleCheckFilled, CircleCloseFilled, Delete, Edit, InfoFilled, Plus, Search, WarningFilled } from '@element-plus/icons-vue';
import { useStockCountStore } from '@/stores/stockCount';

const queryForm = reactive<StockQueryForm>({
    goods_id: null as any,
    goods_name: '',
    warning_threshold: null,
    stock_status: '',
    remarks: ''
});

const stockList = ref<Stock[]>([
    { goods_id: 1, goods_name: '商品A', warning_threshold: 10, stock_quantity: 100, stock_status: '充足', remarks: '备注A' },
    { goods_id: 2, goods_name: '商品B', warning_threshold: 5, stock_quantity: 50, stock_status: '紧张', remarks: '备注B' },
    { goods_id: 3, goods_name: '商品C', warning_threshold: 2, stock_quantity: 0, stock_status: '缺货', remarks: '备注C' }
]);
const total = ref(stockList.value.length);
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);

// 分页后的库存列表
const paginatedStockList = computed(() => {
    if (!stockList.value || stockList.value.length === 0) {
        return [];
    }
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return stockList.value.slice(start, end);
});

const stockCountStore = useStockCountStore();
// 更新缺货和紧张库存数量
const updateStockCount = () => {
    const outOfStockCount = stockList.value.filter(item => item.stock_status === '缺货').length;
    const lowStockCount = stockList.value.filter(item => item.stock_status === '紧张').length;
    stockCountStore.updateStockCount(outOfStockCount, lowStockCount);
};

// 获取建议
function fetchSuggestions(field: keyof StockQueryForm): (queryString: string, cb: (suggestions: { value: string }[]) => void) => void {
    return async (queryString: string, cb: (suggestions: { value: string }[]) => void) => {
        if (!queryString) {
            cb([]);
            return;
        }
        try {
            const response = await axios.get(`/api/stock/suggestions`, {
                params: { field, query: queryString }
            });
            cb(response.data.map((item: string) => ({ value: item })));
        } catch (error) {
            console.error(`获取${field}建议失败:`, error);
            cb([]);
        }
    };
}

// 查询库存信息
async function searchStock() {
    loading.value = true;
    try {
        const response = await axios.get('/api/stock', {
            params: {
                ...queryForm,
                page: 1,
                pageSize: 1000 // 假设最大查询1000条数据
            }
        });
        stockList.value = response.data.items;
        total.value = response.data.total;
        currentPage.value = 1;
        updateStockCount();
        ElMessage.success('查询库存信息成功');
    } catch (error: any) {
        console.error('查询库存信息失败:', error);
        ElMessage.error('查询库存信息失败' + error.response.data.error);
    } finally {
        loading.value = false;
    }
}

// 处理分页变化
function handlePageChange(page: number) {
    currentPage.value = page;
}

function handleSizeChange(size: number) {
    pageSize.value = size;
    currentPage.value = 1;
}

const addStockDialog = ref();
const editStockDialog = ref();
const deleteStockDialog = ref();

// 新建库存信息记录
function openAddDialog() {
    addStockDialog.value.openDialog({
        title: '新建库存信息记录',
        formItems: [
            { label: '商品名称', prop: 'goods_name', value: '', rules: [
                { required: true, message: '商品名称不能为空', trigger: 'blur' },
                { max: 50, message: '商品名称长度不能超过50个字符', trigger: 'blur' }
            ] },
            { label: '预警阈值', prop: 'warning_threshold', value: null, rules: [
                { required: true, message: '预警阈值不能为空', trigger: 'blur' },
                { type: 'number', min: 0, message: '预警阈值不能小于0', trigger: 'blur' }
            ] },
            { label: '库存数量', prop: 'stock_quantity', value: null, rules: [
                { required: true, message: '库存数量不能为空', trigger: 'blur' },
                { type: 'number', min: 0, message: '库存数量不能小于0', trigger: 'blur' }
            ] },
            { label: '备注', prop: 'remarks', value: '', rules: [
                { max: 50, message: '备注长度不能超过50个字符', trigger: 'blur' }
            ] }
        ],
        handleCancel: () => {
            addStockDialog.value.visible = false;
            ElMessage({
                message: '已取消新建',
                type: 'info',
            });
        },
        handleSubmit: async () => {
            try {
                await addStockDialog.value.formRef.validate();
                await axios.post('/api/stock', addStockDialog.value.formData);
                ElMessage({
                    message: '新建库存信息记录成功',
                    type: 'success',
                });
                addStockDialog.value.visible = false;
                searchStock();
            } catch (error: any) {
                console.error('操作失败:', error);
                ElMessage({
                    message: '操作失败 ' + error.response.data.error,
                    type: 'error',
                });
            }
        },
        fetchSuggestions,
    });
}

// 编辑库存信息记录
function openEditDialog(row: Stock) {
    editStockDialog.value.openDialog({
        title: '编辑库存信息记录',
        formItems: [
            { label: '商品名称', prop: 'goods_name', value: row.goods_name, rules: [
                { required: true, message: '商品名称不能为空', trigger: 'blur' },
                { max: 50, message: '商品名称长度不能超过50个字符', trigger: 'blur' }
            ] },
            { label: '预警阈值', prop: 'warning_threshold', value: row.warning_threshold, rules: [
                { required: true, message: '预警阈值不能为空', trigger: 'blur' },
                { type: 'number', min: 0, message: '预警阈值不能小于0', trigger: 'blur' }
            ] },
            { label: '库存数量', prop: 'stock_quantity', value: row.stock_quantity, rules: [
                { required: true, message: '库存数量不能为空', trigger: 'blur' },
                { type: 'number', min: 0, message: '库存数量不能小于0', trigger: 'blur' }
            ] },
            { label: '备注', prop: 'remarks', value: row.remarks, rules: [
                { max: 50, message: '备注长度不能超过50个字符', trigger: 'blur' }
            ] }
        ],
        handleCancel: () => {
            editStockDialog.value.visible = false;
            ElMessage({
                message: '已取消编辑',
                type: 'info',
            });
        },
        handleSubmit: async () => {
            try {
                await editStockDialog.value.formRef.validate();
                await axios.put(`/api/stock/${row.goods_id}`, editStockDialog.value.formData);
                ElMessage({
                    message: '编辑库存信息记录成功',
                    type: 'success',
                });
                editStockDialog.value.visible = false;
                searchStock();
            } catch (error: any) {
                console.error('操作失败:', error);
                ElMessage({
                    message: '操作失败 ' + error.response.data.error,
                    type: 'error',
                });
            }
        },
        fetchSuggestions,
    });
}

// 删除库存信息记录
function openDeleteDialog(row: Stock) {
    deleteStockDialog.value.openDialog({
        title: '删除库存信息记录',
        content: `是否删除商品ID为 ${row.goods_id} 的记录？`,
        handleCancel: () => {
            deleteStockDialog.value.visible = false;
            ElMessage({
                message: '已取消删除',
                type: 'info',
            });
        },
        handleSubmit: async () => {
            try {
                await axios.delete(`/api/stock/${row.goods_id}`);
                ElMessage({
                    message: '删除库存信息记录成功',
                    type: 'success',
                });
                deleteStockDialog.value.visible = false;
                searchStock();
            } catch (error: any) {
                console.error('操作失败:', error);
                ElMessage({
                    message: '操作失败 ' + error.response.data.error,
                    type: 'error',
                });
            }
        }
    });
}

// 根据库存状态获取对应的颜色和图标
function getStatus(status: string) {
    switch (status) {
        case '充足':
            return { type: 'success', color: '#67C23A', icon: CircleCheckFilled };
        case '紧张':
            return { type: 'warning', color: '#E6A23C', icon: WarningFilled };
        case '缺货':
            return { type: 'danger', color: '#F56C6C', icon: CircleCloseFilled };
        default:
            return { type: 'info', color: '#909399', icon: InfoFilled };
    }
}

// 根据库存状态设置行的样式
function tableRowClassName({ row }: { row: any }) {
    if (row.stock_status === '缺货') {
        return 'row-out-of-stock';
    } else if (row.stock_status === '紧张') {
        return 'row-low-stock';
    } else if (row.stock_status === '充足') {
        return 'row-in-stock';
    }
    return '';
}

onMounted(() => {
    // 初始化时加载数据
    searchStock();
});
</script>

<style scoped>
.el-form-item {
    margin: 10px 0;
}
.el-input,
.el-button {
    width: 100%;
}
.el-form {
    padding: 20px;
}
.el-form-item .el-form-item__label {
    padding-right: 20px;
}
/* 必须deep */
:deep() .el-table .row-out-of-stock {
    background-color: #f8d7da; 
}
:deep() .el-table .row-low-stock {
    background-color: #fff3cd;
}
:deep() .el-table .row-in-stock {
    background-color: #d1e7dd;
}
/* 必须important */
:deep() .el-table tbody tr:hover>td { 
    background-color:#c2e8f9!important;
}
</style>